// pages/index/index.js
Page({
  data: {
    motto: '欢迎使用神算子AI助手',
    userInfo: {},
    hasUserInfo: false,
    avatarUrl: '',
    nickName: '',
    canConfirm: false
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    
    // 检查是否已有用户信息
    this.checkExistingUserInfo()
  },
  
  // 检查已存在的用户信息
  checkExistingUserInfo() {
    const userAvatarUrl = wx.getStorageSync('userAvatarUrl')
    const userNickName = wx.getStorageSync('userNickName')
    const hasUserInfo = wx.getStorageSync('hasUserInfo')
    
    if (hasUserInfo && userAvatarUrl && userNickName) {
      // 检查头像文件是否仍然存在
      if (userAvatarUrl.includes(wx.env.USER_DATA_PATH)) {
        try {
          const fs = wx.getFileSystemManager()
          fs.accessSync(userAvatarUrl)
          // 文件存在，设置用户信息
          this.setData({
            userInfo: {
              avatarUrl: userAvatarUrl,
              nickName: userNickName
            },
            hasUserInfo: true
          })
          return
        } catch (error) {
          console.log('头像文件不存在，清除缓存:', error)
          // 文件不存在，清除缓存
          wx.removeStorageSync('userAvatarUrl')
          wx.removeStorageSync('userNickName')
          wx.removeStorageSync('hasUserInfo')
          return
        }
      } else {
        // 临时文件路径，直接设置（可能已过期但先尝试显示）
        this.setData({
          userInfo: {
            avatarUrl: userAvatarUrl,
            nickName: userNickName
          },
          hasUserInfo: true
        })
      }
    }
  },

  // 选择头像回调
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    console.log('选择的头像:', avatarUrl)
    this.setData({
      avatarUrl: avatarUrl
    })
    this.checkCanConfirm()
    
    wx.showToast({
      title: '头像选择成功',
      icon: 'success',
      duration: 1500
    })
  },

  // 昵称输入回调
  onNicknameInput(e) {
    const nickName = e.detail.value
    this.setData({
      nickName: nickName
    })
    this.checkCanConfirm()
  },
  
  // 昵称输入失焦回调
  onNicknameBlur(e) {
    const nickName = e.detail.value.trim()
    this.setData({
      nickName: nickName
    })
    this.checkCanConfirm()
  },
  
  // 检查是否可以确认
  checkCanConfirm() {
    const { avatarUrl, nickName } = this.data
    const canConfirm = avatarUrl && nickName && nickName.trim().length > 0
    this.setData({
      canConfirm: canConfirm
    })
  },
  
  // 确认用户信息
  confirmUserInfo() {
    const { avatarUrl, nickName } = this.data
    
    if (!avatarUrl) {
      wx.showToast({
        title: '请选择头像',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    if (!nickName || nickName.trim().length === 0) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 上传头像到服务器或保存临时路径
    this.uploadAvatar(avatarUrl, nickName.trim())
  },
  
  // 上传头像
  uploadAvatar(tempFilePath, nickName) {
    wx.showLoading({
      title: '保存中...'
    })
    
    // 将临时文件保存到本地永久目录
    const fs = wx.getFileSystemManager()
    const savedPath = `${wx.env.USER_DATA_PATH}/avatar_${Date.now()}.jpg`
    
    try {
      // 复制临时文件到永久目录
      fs.copyFileSync(tempFilePath, savedPath)
      
      const userInfo = {
        avatarUrl: savedPath,
        nickName: nickName
      }
      
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      
      // 保存到本地存储
      wx.setStorageSync('userAvatarUrl', savedPath)
      wx.setStorageSync('userNickName', nickName)
      wx.setStorageSync('hasUserInfo', true)
      
      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    } catch (error) {
      console.error('保存头像失败:', error)
      // 如果保存失败，仍然使用临时路径
      const userInfo = {
        avatarUrl: tempFilePath,
        nickName: nickName
      }
      
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      
      wx.setStorageSync('userAvatarUrl', tempFilePath)
      wx.setStorageSync('userNickName', nickName)
      wx.setStorageSync('hasUserInfo', true)
      
      wx.hideLoading()
      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    }
  },
  
  // 重新设置用户信息
  resetUserInfo() {
    // 删除本地保存的头像文件
    const savedAvatarUrl = wx.getStorageSync('userAvatarUrl')
    if (savedAvatarUrl && savedAvatarUrl.includes(wx.env.USER_DATA_PATH)) {
      try {
        const fs = wx.getFileSystemManager()
        fs.unlinkSync(savedAvatarUrl)
      } catch (error) {
        console.log('删除头像文件失败:', error)
      }
    }
    
    this.setData({
      hasUserInfo: false,
      avatarUrl: '',
      nickName: '',
      canConfirm: false
    })
    
    // 清除本地存储
    wx.removeStorageSync('userAvatarUrl')
    wx.removeStorageSync('userNickName')
    wx.removeStorageSync('hasUserInfo')
    
    wx.showToast({
      title: '已重置用户信息',
      icon: 'success',
      duration: 1500
    })
  },

  // 跳转到聊天页面
  goToChat() {
    wx.switchTab({
      url: '/pages/chat/chat'
    })
  }
})